package com.xzz.directprint.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.xzz.directprint.domain.AjaxResult;
import com.xzz.directprint.util.FileUtil;
import com.xzz.directprint.util.PdfPrinter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.awt.print.PrinterException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zhanglm
 * @CreateDate: 2024-11-17 14:43
 * @FullNameClass: com.xzz.directprint.controller.PdfController
 * @Description:
 */
@RestController
@RequestMapping("/xzz")
public class PdfController {


    Logger logger = LoggerFactory.getLogger(PdfController.class);


    @Value("${pdf.path}")
    private String pdfpath;

    @Value("${pdf.expanded-name}")
    private String expandName;

    @PostMapping("/print")
    @ResponseBody
    public AjaxResult pdf2Print(@RequestBody String params){

//        FileUtil.writeFile(pdfpath, "json.txt",params);
        JSONObject jsonObject = JSON.parseObject(params);
        JSONObject jsonData = JSON.parseObject(jsonObject.get("data").toString());
        Object picno1 = jsonData.get("picno");
        if(picno1 == null){
            System.out.println("未给出图号名称");
            return AjaxResult.error("图号不存在");
        }
        String[] picno = picno1.toString().split(",");
        List<String> listSuccess = new ArrayList<>();
        List<String> listError = new ArrayList<>();
        boolean bool = true;
        for (int i = 0; i < picno.length; i++){

            /**
             * 修改逻辑
             * 1、根据图号查询文件名，获取到对应图号的文件（文件名+扩展名）
             * 2、如果有对应pdf格式，直接进行打印；
             *    如果有图片，也可直接打印，
             *    如果是AutoCad格式，需要先转换成jpg格式，然后删除cad格式文件，然后再打印jpg
             *
             *
             */
            try {
                String file = pdfpath.concat(picno[i]).concat(expandName);
                bool = PdfPrinter.printPdf(file);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (PrinterException e) {
                throw new RuntimeException(e);
            }
            if (bool){
                listError.add(picno[i]);
            }else {
                listSuccess.add(picno[i]);
            }
        }
        logger.info("打印成功：" + listSuccess.toString());
        logger.info("打印失败：" + listError.toString());
        return AjaxResult.success();
    }

}
